package com.sifou.courses.config;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.sifou.courses.cache.LocalCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @author liuzhongxu
 * @date 2020/9/1
 */
@Slf4j
@Configuration
public class CaffeineCacheConfig {

    private static final long CAFFEINE_EXPIRE_TIME = 1;
    private static final long CAFFEINE_REFRESH_TIME = 1;
    private static final long CAFFEINE_MAXSIZE = 1024;


    @Bean
    public CacheManager CaffeineCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();

        cacheManager.setCaffeine(Caffeine.newBuilder()
                .refreshAfterWrite(CAFFEINE_REFRESH_TIME, TimeUnit.SECONDS)
                .maximumSize(CAFFEINE_MAXSIZE));
        cacheManager.setCacheLoader(new CacheLoader<Object, Object>() {

            @Override
            public Object load(Object key) throws Exception {
                log.debug("cacheLoader load key={}", key);
                LocalCache localCache = new LocalCache();
                localCache.setKey(key);
                localCache.setValue(null);
                localCache.setNeedReload(true);
                return localCache;
            }

            // 重写这个方法将oldValue值返回回去，进而刷新缓存
            @Override
            public Object reload(Object key, Object oldValue) throws Exception {
                log.debug("cacheLoader reload key={} oldValue={}", key, oldValue);
                LocalCache localCache = (LocalCache) oldValue;
                localCache.setNeedReload(true);
                return localCache;
            }
        });

        return cacheManager;
    }

}
